package com.library.common.utils;


import com.google.gson.Gson;
import com.library.util.MD5Util;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

/**
 * 封装http get post
 */
public class HttpUtils {


    private static  final Gson gson = new Gson();

    /**
     * get方法
     * @param url
     * @return
     */
    public static Map<String,Object> doGet(String url){

        Map<String,Object> map = new HashMap<>();
        CloseableHttpClient httpClient =  HttpClients.createDefault();

        RequestConfig requestConfig =  RequestConfig.custom().setConnectTimeout(5000) //连接超时
                .setConnectionRequestTimeout(5000)//请求超时
                .setSocketTimeout(5000)
                .setRedirectsEnabled(true)  //允许自动重定向
                .build();

        HttpGet httpGet = new HttpGet(url);
        httpGet.setConfig(requestConfig);

        try{
           HttpResponse httpResponse = httpClient.execute(httpGet);
           if(httpResponse.getStatusLine().getStatusCode() == 200){

              String jsonResult = EntityUtils.toString( httpResponse.getEntity());
               map = gson.fromJson(jsonResult,map.getClass());
           }

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                httpClient.close();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return map;
    }
    public static String doGet1(String url){
        String jsonResult="";
        Map<String,Object> map = new HashMap<>();
        CloseableHttpClient httpClient =  HttpClients.createDefault();

        RequestConfig requestConfig =  RequestConfig.custom().setConnectTimeout(5000) //连接超时
                .setConnectionRequestTimeout(5000)//请求超时
                .setSocketTimeout(5000)
                .setRedirectsEnabled(true)  //允许自动重定向
                .build();

        HttpGet httpGet = new HttpGet(url);
        httpGet.setConfig(requestConfig);

        try{
            HttpResponse httpResponse = httpClient.execute(httpGet);
            if(httpResponse.getStatusLine().getStatusCode() == 200){

                jsonResult = EntityUtils.toString( httpResponse.getEntity());
            }

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                httpClient.close();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return jsonResult;
    }


    /**
     * 封装post
     * @return
     */
    public static String doPost(String url, String data,int timeout){
        CloseableHttpClient httpClient =  HttpClients.createDefault();
        //超时设置

        RequestConfig requestConfig =  RequestConfig.custom().setConnectTimeout(timeout) //连接超时
                .setConnectionRequestTimeout(timeout)//请求超时
                .setSocketTimeout(timeout)
                .setRedirectsEnabled(true)  //允许自动重定向
                .build();


        HttpPost httpPost  = new HttpPost(url);
        httpPost.setConfig(requestConfig);
        httpPost.addHeader("Content-Type","text/html; chartset=UTF-8");

        if(data != null && data instanceof  String){ //使用字符串传参
            StringEntity stringEntity = new StringEntity(data,"UTF-8");
            httpPost.setEntity(stringEntity);
        }

        try{

            CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            if(httpResponse.getStatusLine().getStatusCode() == 200){
                String result = EntityUtils.toString(httpEntity);
                return result;
            }

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try{
                httpClient.close();
            }catch (Exception e){
                e.printStackTrace();
            }
        }

        return null;

    }


    /**
     * 封装post
     * @return
     */
    public static String doPost1(String url, String data){
        CloseableHttpClient httpClient =  HttpClients.createDefault();
        //超时设置

        RequestConfig requestConfig =  RequestConfig.custom().setConnectTimeout(5000) //连接超时
                .setConnectionRequestTimeout(5000)//请求超时
                .setSocketTimeout(5000)
                .setRedirectsEnabled(true)  //允许自动重定向
                .build();

        //这里上生产得话需要切换成正式环境
        HttpPost httpPost  = new HttpPost("https://demo.mojicb.com"+url);
        httpPost.setConfig(requestConfig);
//        httpPost.addHeader("Content-Type","text/html; chartset=UTF-8");
        String token="94b6614e8941aa502471110cba168370";
        String pwd="03e4e7c26a7ab2d85b4456429bf55e98";
        long timestamp = System.currentTimeMillis() ;
        String randStrCode = RandomCodeUtil.getRandStrCode(20);
        String md5 = MD5Util.getMd5(pwd + '\n' + timestamp + '\n' + randStrCode + '\n' + url);
        httpPost.addHeader("X-AC-Token",token);
        httpPost.addHeader("X-Date",timestamp+"");
        httpPost.addHeader("X-AC-Nonce",randStrCode);
        httpPost.addHeader("X-AC-Signature",md5);

        if(data != null && data instanceof  String){ //使用字符串传参
            StringEntity stringEntity = new StringEntity(data,"UTF-8");
            httpPost.setEntity(stringEntity);
        }

        try{

            CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            if(httpResponse.getStatusLine().getStatusCode() == 200){
                String result = EntityUtils.toString(httpEntity);
                return result;
            }

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try{
                httpClient.close();
            }catch (Exception e){
                e.printStackTrace();
            }
        }

        return null;

    }

//    public static void main(String args[]) throws Exception {
////    sendPostRequest("/tob-data-misc/eshop/access/creation","{\"orderId\":\"DDMX-240918-0010\",\"region\":\"GC27W\",\"type\":\"CITY\",\"rate\":\"D150W\",\"duration\":\"N2Y\",\"validStartTime\":\"20240919000000\",\"endpoints\":[\"GC27W_24H\"]}");
////    }
        public static String sendPostRequest(String urlString, String postData) throws Exception {
            URL url = new URL("https://demo.mojicb.com"+urlString);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            connection.setRequestMethod("POST");
            connection.setDoOutput(true);
            String token="94b6614e8941aa502471110cba168370";
            String pwd="03e4e7c26a7ab2d85b4456429bf55e98";
            long timestamp = System.currentTimeMillis() ;
            String randStrCode = RandomCodeUtil.getRandStrCode(20);
            String md5 = MD5Util.getMd5(pwd + '\n' + timestamp + '\n' + randStrCode + '\n' + urlString);
            connection.setRequestProperty("X-AC-Token",token);
            connection.setRequestProperty("X-Date",timestamp+"");
            connection.setRequestProperty("X-AC-Nonce",randStrCode);
            connection.setRequestProperty("X-AC-Signature",md5);
            connection.setRequestProperty("Content-Type", "application/json");



            OutputStream outputStream = connection.getOutputStream();
            outputStream.write(postData.getBytes("UTF-8"));
            outputStream.flush();
            outputStream.close();

            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            StringBuilder response = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            reader.close();

            connection.disconnect();

            return response.toString();
        }

    public static String doGet2(String url){
        String jsonResult="";
        Map<String,Object> map = new HashMap<>();
        CloseableHttpClient httpClient =  HttpClients.createDefault();

        RequestConfig requestConfig =  RequestConfig.custom().setConnectTimeout(5000) //连接超时
                .setConnectionRequestTimeout(5000)//请求超时
                .setSocketTimeout(5000)
                .setRedirectsEnabled(true)  //允许自动重定向
                .build();

        HttpGet httpGet = new HttpGet(url);
        httpGet.setConfig(requestConfig);
        String token="94b6614e8941aa502471110cba168370";
        String pwd="03e4e7c26a7ab2d85b4456429bf55e98";
        long timestamp = System.currentTimeMillis() ;
        String randStrCode = RandomCodeUtil.getRandStrCode(20);
        String md5 = MD5Util.getMd5(pwd + '\n' + timestamp + '\n' + randStrCode + '\n' + "/eshop-statistic/v1/mds-brief");
        httpGet.setHeader("X-AC-Token",token);
        httpGet.setHeader("X-Date",timestamp+"");
        httpGet.setHeader("X-AC-Nonce",randStrCode);
        httpGet.setHeader("X-AC-Signature",md5);
        httpGet.setHeader("Content-Type", "application/json");
        try{
            HttpResponse httpResponse = httpClient.execute(httpGet);
            if(httpResponse.getStatusLine().getStatusCode() == 200){

                jsonResult = EntityUtils.toString( httpResponse.getEntity());
            }

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                httpClient.close();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return jsonResult;
    }
    public static String doGet3(String url){
        String jsonResult="";
        Map<String,Object> map = new HashMap<>();
        CloseableHttpClient httpClient =  HttpClients.createDefault();

        RequestConfig requestConfig =  RequestConfig.custom().setConnectTimeout(5000) //连接超时
                .setConnectionRequestTimeout(5000)//请求超时
                .setSocketTimeout(5000)
                .setRedirectsEnabled(true)  //允许自动重定向
                .build();

        HttpGet httpGet = new HttpGet(url);
        httpGet.setConfig(requestConfig);
        String token="94b6614e8941aa502471110cba168370";
        String pwd="03e4e7c26a7ab2d85b4456429bf55e98";
        long timestamp = System.currentTimeMillis() ;
        String randStrCode = RandomCodeUtil.getRandStrCode(20);
        String md5 = MD5Util.getMd5(pwd + '\n' + timestamp + '\n' + randStrCode + '\n' + "/eshop-statistic/v1/mds-tsdata");
        httpGet.setHeader("X-AC-Token",token);
        httpGet.setHeader("X-Date",timestamp+"");
        httpGet.setHeader("X-AC-Nonce",randStrCode);
        httpGet.setHeader("X-AC-Signature",md5);
        httpGet.setHeader("Content-Type", "application/json");
        try{
            HttpResponse httpResponse = httpClient.execute(httpGet);
            if(httpResponse.getStatusLine().getStatusCode() == 200){

                jsonResult = EntityUtils.toString( httpResponse.getEntity());
            }

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                httpClient.close();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return jsonResult;
    }

    public static String doGet4(String url){
        String jsonResult="";
        Map<String,Object> map = new HashMap<>();
        CloseableHttpClient httpClient =  HttpClients.createDefault();

        RequestConfig requestConfig =  RequestConfig.custom().setConnectTimeout(5000) //连接超时
                .setConnectionRequestTimeout(5000)//请求超时
                .setSocketTimeout(5000)
                .setRedirectsEnabled(true)  //允许自动重定向
                .build();

        HttpGet httpGet = new HttpGet(url);
        httpGet.setConfig(requestConfig);
        String token="94b6614e8941aa502471110cba168370";
        String pwd="03e4e7c26a7ab2d85b4456429bf55e98";
        long timestamp = System.currentTimeMillis() ;
        String randStrCode = RandomCodeUtil.getRandStrCode(20);
        String md5 = MD5Util.getMd5(pwd + '\n' + timestamp + '\n' + randStrCode + '\n' + "/tob-data-misc/eshop/access/enums");
        httpGet.setHeader("X-AC-Token",token);
        httpGet.setHeader("X-Date",timestamp+"");
        httpGet.setHeader("X-AC-Nonce",randStrCode);
        httpGet.setHeader("X-AC-Signature",md5);
        httpGet.setHeader("Content-Type", "application/json");
        try{
            HttpResponse httpResponse = httpClient.execute(httpGet);
            if(httpResponse.getStatusLine().getStatusCode() == 200){

                jsonResult = EntityUtils.toString( httpResponse.getEntity());
            }

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                httpClient.close();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return jsonResult;
    }
}
